//
//  HZProductConfirmView.m
//  app
//
//  Created by 刘华舟 on 15/6/24.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZProductConfirmView.h"
#import "UIImageView+URL.h"
#import "UILabel+Conveniently.h"

#import "HZProductSpecView.h"
#import "MyToast.h"

#import "HZGoodsDetailHeadModel.h"

static const NSInteger kMainViewBaseHeight = 300;
static const NSInteger kScrollViewMaxHeight = 680;
static const NSInteger kProductPictureWidth = 150;
static const NSInteger kDismissBtnWidth = 80;
static const NSInteger kConfirmButtonHeight = 90;
static const NSInteger kPriceLabelHeight = 42;
static const NSInteger kTitleLabelHeight = 62;

static const NSInteger kMaxNumLabelHeight = kMainViewBaseHeight-kConfirmButtonHeight-kProductPictureWidth+kSizeMallViewMargin;
static const NSInteger kCounterWidth = 172;
static const CGFloat kCounterHeight = 25.0f;

static const NSInteger kCounterBtnWidth = 90;



@interface HZProductConfirmView()


@property (strong, nonatomic) UIView *backView;

@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UIImageView *productAvatar;
@property (strong, nonatomic) UILabel *maxNumLabel;//购买数量库存量
@property (strong, nonatomic) UILabel *counterLabel;
@property (strong, nonatomic) UILabel *priceLabel;
@property (strong, nonatomic) UILabel *titleLabel;

@property (strong, nonatomic) UIView *lineView;

@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) HZProductSpecView *specView;


@property (strong, nonatomic) UIButton *confirmBtn;

@property (assign, nonatomic) CGFloat scrollViewHeight;

@property (strong, nonatomic) HZGoodsDetailHeadModel *model;

@end

@implementation HZProductConfirmView

- (instancetype)initWithDetailHeadModel:(HZGoodsDetailHeadModel *)model{
    CGRect frame = CGRectOf([UBO_WINDOW fx:UB_LEFT fy:UB_TOP], [UBO_WINDOW fw:UB_WIDTH fh:UB_HEIGHT]);
    if (self = [super initWithFrame:frame]) {
        
        self.model = model;
        
        self.backgroundColor = HZ_CLEAR_COLOR;
        self.scrollViewHeight = 0.0f;
        self.backView = [[UIView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                               [self.ubo fw:UB_WIDTH fh:UB_HEIGHT])];
        self.backView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.8f];
        self.backView.alpha = 0.0f;
        [self addSubview:self.backView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissProductGiftView)];
        [self.backView addGestureRecognizer:tapGesture];
        
        //背景视图
        self.contentView = [[UIView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_BOTTOM uy:kSizeMallViewMargin],
                                                                   [self.ubo fw:UB_WIDTH uh:kMainViewBaseHeight])];
        self.contentView.backgroundColor = HZ_WHITE_COLOR;
        [self addSubview:self.contentView];
        
        //商品图像
        self.productAvatar = [[UIImageView alloc] initWithFrame:CGRectOf([self.contentView.ubo ux:kSizeMallViewMargin uy:-kSizeMallViewMargin],
                                                                                 [self.contentView.ubo uw:kProductPictureWidth uh:kProductPictureWidth])];
        self.productAvatar.backgroundColor = HZ_WHITE_COLOR;
        self.productAvatar.layer.masksToBounds = YES;
        self.productAvatar.layer.borderColor = HZ_MALL_BORDER_LINE_GRAY_COLOR.CGColor;
        self.productAvatar.layer.borderWidth = [self.productAvatar.ubo ph:1];
        [self.productAvatar setImageWithURL:model.topModel.productPic];
        [self.contentView addSubview:self.productAvatar];
        
        //消失按钮
        UIButton *dismissBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.contentView.ubo fx:UB_RIGHT ux:-kSizeMallViewMargin-kDismissBtnWidth fy:UB_TOP uy:kSizeMallViewMargin],
                                                                        [self.contentView.ubo uw:kDismissBtnWidth uh:kDismissBtnWidth])];
        [dismissBtn setImage:[UIImage imageNamed:kImageButtonDeleteXGary] forState:UIControlStateNormal];
        dismissBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        dismissBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
        [dismissBtn addTarget:self action:@selector(dismissProductGiftView) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:dismissBtn];
        
        //商品价格
        self.priceLabel = [[UILabel alloc] initWithFrame:CGRectOf([self.contentView.ubo ux:kSizeMallViewMargin*2+kProductPictureWidth uy:kSizeMallViewMargin],
                                                                      [self.contentView.ubo fw:UB_WIDTH uw:-3*kSizeMallViewMargin-kProductPictureWidth uh:kPriceLabelHeight])];
        
        self.priceLabel.textAlignment = NSTextAlignmentLeft;
        self.priceLabel.textColor = HZ_MALL_MAIN_THEME_ORANGE;
        self.priceLabel.font = kHZUFont_Menu_S;
        self.priceLabel.text = [NSString stringWithFormat:@"￥%@", model.topModel.salePrice];
        [self.contentView addSubview:self.priceLabel];
        
        //商品名称
        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectOf([self.priceLabel.ufo fx:UB_LEFT fy:UB_BOTTOM],
                                                                    [self.priceLabel.ubo fw:UB_WIDTH uh:kTitleLabelHeight])];
        
        self.titleLabel.textAlignment = NSTextAlignmentLeft;
        self.titleLabel.textColor = HZ_MALL_TEXT_M_LIGHTGRAY_COLOR;
        self.titleLabel.numberOfLines = 2;
        self.titleLabel.font = kHZUFont_Tag_L;
        self.titleLabel.text = model.topModel.productTitle;
        [self.contentView addSubview:self.titleLabel];
        [self.titleLabel labelTextAlignTop];
        
        //购买数量
        self.maxNumLabel = [[UILabel alloc] initWithFrame:CGRectOf([self.contentView.ubo fx:UB_LEFT ux:kSizeMallViewMargin fy:UB_BOTTOM uy:-kMaxNumLabelHeight-kConfirmButtonHeight],
                                                                       [self.contentView.ubo fw:UB_WIDTH uw:-2*kSizeMallViewMargin uh:kMaxNumLabelHeight])];
        //NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"购买数量（库存%@件）", model.topModel.num]];
        /** 去掉库存数量显示 -wirte by khzliu */
        
        NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"购买数量"];
        
        [attriStr addAttribute:NSFontAttributeName value:kHZUFont_Content_M range:NSMakeRange(0, 4)];
        [attriStr addAttribute:NSForegroundColorAttributeName value:HZ_MALL_TEXT_BLACK_COLOR range:NSMakeRange(0, 4)];
        [attriStr addAttribute:NSFontAttributeName value:kHZUFont_Tag_L range:NSMakeRange(4, attriStr.length-4)];
        [attriStr addAttribute:NSForegroundColorAttributeName value:HZ_MALL_TEXT_M_LIGHTGRAY_COLOR range:NSMakeRange(4, attriStr.length-4)];
        self.maxNumLabel.attributedText = attriStr;
        [self.contentView addSubview:self.maxNumLabel];
        
        
        //计数器
        UIImageView *backCounterView = [[UIImageView alloc] initWithFrame:CGRectOf([self.maxNumLabel.ufo fx:UB_RIGHT ux:-kCounterWidth fy:UB_CENTER oy:-kCounterHeight/2],
                                                                                   [self.maxNumLabel.ubo uw:kCounterWidth oh:kCounterHeight])];
        UIImage *counterImage = [[UIImage imageNamed:kImageGoodsDetailNumCounterTaoBao] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 42, 0, 42) resizingMode:UIImageResizingModeStretch];
        
        [backCounterView setImage:counterImage];
        
        [self.contentView addSubview:backCounterView];
        
        self.counterLabel = [[UILabel alloc] initWithFrame:CGRectOf([backCounterView.ubo fx:UB_LEFT fy:UB_TOP],
                                                                    [backCounterView.ubo fw:UB_WIDTH fh:UB_HEIGHT])];
        self.counterLabel.textAlignment = NSTextAlignmentCenter;
        self.counterLabel.textColor = HZ_MALL_TEXT_L_LIGHTGRAY_COLOR;
        self.counterLabel.text = [NSString stringWithFormat:@"%ld", (long)model.topModel.buyNum];
        self.counterLabel.font = JKAppGlobleFontSmallTagText;
        [backCounterView addSubview:self.counterLabel];
        
        
        UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRectOf([backCounterView.ufo fx:UB_RIGHT ux:-kCounterBtnWidth/2 fy:UB_TOP],
                                                                    [self.maxNumLabel.ubo uw:kCounterBtnWidth fh:UB_HEIGHT])];
        [addBtn addTarget:self action:@selector(addBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:addBtn];
        
        UIButton *reduceBtn = [[UIButton alloc] initWithFrame:CGRectOf([backCounterView.ufo fx:UB_LEFT ux:-kCounterBtnWidth/2 fy:UB_TOP],
                                                                       [self.maxNumLabel.ubo uw:kCounterBtnWidth fh:UB_HEIGHT])];
        
        [reduceBtn addTarget:self action:@selector(reduceBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:reduceBtn];
        
        
        //下滑线
        self.lineView = [[UIView alloc] initWithFrame:CGRectOf([self.contentView.ubo fx:UB_LEFT fy:UB_BOTTOM uy:-kConfirmButtonHeight py:-0.5],
                                                                  [self.contentView.ubo fw:UB_WIDTH ph:0.5])];
        self.lineView.backgroundColor = HZ_MALL_M_SEPARATOR_CELL_LINE;
        [self.contentView addSubview:self.lineView];
        
        
        
        self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectOf([self.lineView.ufo fx:UB_LEFT fy:UB_BOTTOM], [self.contentView.ubo fw:UB_WIDTH uh:kScrollViewMaxHeight])];
        self.scrollView.backgroundColor = HZ_WHITE_COLOR;
        [self.contentView addSubview:self.scrollView];
        
        self.specView = [[HZProductSpecView alloc] initWithFrame:CGRectOf([self.scrollView.ubo fx:UB_LEFT fy:UB_TOP], CGSizeZero)];
        [self.specView showCategories:model.patterns withTitleKey:APIKEY_mall_name default:model.defaultPattern];
        self.specView.tabSelectedCaller = [UBTargetCaller of:self action:@selector(choseOneSelected:)];
        
        [self.scrollView addSubview:self.specView];
        
        
        if (model.patterns.count) {
            self.specView.frame = CGRectOf([self.scrollView.ubo fx:UB_LEFT fy:UB_TOP],
                                           [self.scrollView.ubo fw:UB_WIDTH oh:model.specificationsViewHeight]);
            [self.specView showCategories:model.patterns withTitleKey:APIKEY_mall_name default:model.defaultPattern];
            
            self.specView.hidden = NO;
        }else{
            self.specView.frame = CGRectOf([self.scrollView.ubo fx:UB_LEFT fy:UB_TOP], [self.scrollView.ubo fw:UB_WIDTH oh:0]);
            self.specView.hidden = YES;
        }
        
        
        

       
        
        [self.model switchPromotionView:model.promotionModel];
        
        if (model.specificationsViewHeight+model.promotionViewHeight < self.scrollView.frame.size.height) {
            self.scrollView.frame = CGRectOf([self.lineView.ufo fx:UB_LEFT fy:UB_BOTTOM], [self.contentView.ubo fw:UB_WIDTH oh:model.specificationsViewHeight+model.promotionViewHeight]);
            self.scrollViewHeight = model.specificationsViewHeight+model.promotionViewHeight;
        }else{
            self.scrollViewHeight = [UBO_WINDOW uh:kScrollViewMaxHeight];
        }
        
        
        self.scrollView.contentSize = [UBO_WINDOW fw:UB_WIDTH oh:model.specificationsViewHeight+model.promotionViewHeight];
        
        
        //重新布局视图
        self.contentView.frame = CGRectOf([self.ubo fx:UB_LEFT fy:UB_BOTTOM uy:kSizeMallViewMargin],
                                          [self.ubo fw:UB_WIDTH uh:kMainViewBaseHeight oh:self.scrollViewHeight]);
        
        //确认按钮
        //消失按钮
        self.confirmBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.contentView.ubo fx:UB_LEFT fy:UB_BOTTOM uy:-kConfirmButtonHeight],
                                                                        [self.contentView.ubo fw:UB_WIDTH uh:kConfirmButtonHeight])];
        [_confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:HZ_WHITE_COLOR forState:UIControlStateNormal];
        _confirmBtn.backgroundColor = HZ_MALL_MAIN_THEME_ORANGE;
        _confirmBtn.titleLabel.font = kHZUFont_TitleBar_S;
        [_confirmBtn addTarget:self action:@selector(confirmBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_confirmBtn];
    }
    return self;
}


#pragma mark private methom
- (void)showGiftListView{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:0.4 animations:^{
        self.backView.alpha = 1.0f;
        self.contentView.frame = CGRectOf([self.ubo fx:UB_LEFT fy:UB_BOTTOM uy:-kMainViewBaseHeight oy:-self.scrollViewHeight],
                                           [self.ubo fw:UB_WIDTH uh:kMainViewBaseHeight oh:self.scrollViewHeight]);
    } completion:^(BOOL finished) {
        
    }];
}
- (void)hideGiftListView{
    [UIView animateWithDuration:0.4 animations:^{
        self.backView.alpha = 0.0f;
        self.contentView.frame = CGRectOf([self.ubo fx:UB_LEFT fy:UB_BOTTOM uy:kSizeMallViewMargin],
                                           [self.ubo fw:UB_WIDTH uh:kMainViewBaseHeight oh:self.scrollViewHeight]);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}


#pragma mark event handler
//点击空白界面 视图消失
- (void)dismissProductGiftView{
    
//    self.promView.model.open = NO;
//    
//    [self.model switchPromotionView:self.promView.model];
    
    if (self.targetCallerPromChange) {
        [self.targetCallerPromChange call:self.model];
    }
    
    
    [self hideGiftListView];
}


//点击确认按钮
- (void)confirmBtnOnClick{
    
    if (self.targetCallerConfirm) {
        [self.targetCallerConfirm call:self.counterLabel.text];
    }
    
    [self dismissProductGiftView];
    
}



- (void)addBtnOnClick{
    
    /** 这里增加测试flag判断 -wirte by khzliu */
    //如果是测试flag 那么就只允许用户购买一个商品
    if ([[SNUniteUrl shareUniteUrl].runMode isEqualToString:kAPPRunModeSoftOpened]) {
        [MyToast showDefaultBottonWithText:@"当前商城为试运营，每种商品限购一件"];
        return;
    }
    
    
    
    if ((self.model.topModel.buyNum+1) > [self.model.topModel.num integerValue]) {
        [MyToast showDefaultBottonWithText:@"数量超出范围~"];
        return;
    }
     self.model.topModel.buyNum++;
    self.counterLabel.text = [NSString stringWithFormat:@"%d", self.model.topModel.buyNum];
}

- (void)reduceBtnOnClick{
    if ((self.model.topModel.buyNum-1) <= 0) {
        [MyToast showDefaultBottonWithText:@"至少选取一件~"];
        return;
    }
    
    self.model.topModel.buyNum--;
    self.counterLabel.text = [NSString stringWithFormat:@"%d", self.model.topModel.buyNum];
}


#pragma mark 点击某一个规格
- (void)choseOneSelected:(NSDictionary *)dict{
    
    if ([dict count]) {
        
        __weak typeof(self) wself = self;
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(changePromotiomWithDict:finished:)]) {
            [self.delegate changePromotiomWithDict:dict finished:^(HZGoodsDetailHeadModel *model){
                
                wself.model = model;
                
                //NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"购买数量（库存%@件）", model.topModel.num]];
                /** 去掉库存数量显示 -wirte by khzliu */
                
                NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"购买数量"];
                [attriStr addAttribute:NSFontAttributeName value:kHZUFont_Content_M range:NSMakeRange(0, 4)];
                [attriStr addAttribute:NSForegroundColorAttributeName value:HZ_MALL_TEXT_BLACK_COLOR range:NSMakeRange(0, 4)];
                [attriStr addAttribute:NSFontAttributeName value:kHZUFont_Tag_L range:NSMakeRange(4, attriStr.length-4)];
                [attriStr addAttribute:NSForegroundColorAttributeName value:HZ_MALL_TEXT_M_LIGHTGRAY_COLOR range:NSMakeRange(4, attriStr.length-4)];
                wself.maxNumLabel.attributedText = attriStr;
                [wself.contentView addSubview:wself.maxNumLabel];
                
                /** 跟新二次确认页面视觉 -wirte by khzliu */
                [wself.productAvatar setImageWithURL:wself.model.topModel.productPic];
                wself.priceLabel.text = [NSString stringWithFormat:@"￥%@", wself.model.topModel.salePrice];
                wself.titleLabel.text = wself.model.topModel.productTitle;
                
                self.counterLabel.text = [NSString stringWithFormat:@"%d", model.topModel.buyNum];
                
                [self.specView showCategories:model.patterns withTitleKey:APIKEY_mall_name default:model.defaultPattern];
                
                
                
                
                
                if (wself.model.specificationsViewHeight+wself.model.promotionModel.topHeight+wself.model.promotionModel.middleHeight+wself.model.promotionModel.bottomHeight < [UBO_WINDOW uh:kScrollViewMaxHeight]) {
                    wself.scrollView.frame = CGRectOf([wself.lineView.ufo fx:UB_LEFT fy:UB_BOTTOM], [wself.contentView.ubo fw:UB_WIDTH oh:wself.model.specificationsViewHeight+wself.model.promotionModel.topHeight+wself.model.promotionModel.middleHeight+wself.model.promotionModel.bottomHeight]);
                    wself.scrollViewHeight = wself.model.specificationsViewHeight+wself.model.promotionModel.topHeight+wself.model.promotionModel.middleHeight+wself.model.promotionModel.bottomHeight;
                }else{
                    wself.scrollView = [[UIScrollView alloc] initWithFrame:CGRectOf([wself.lineView.ufo fx:UB_LEFT fy:UB_BOTTOM],
                                                                                   [wself.contentView.ubo fw:UB_WIDTH uh:kScrollViewMaxHeight])];
                    wself.scrollViewHeight = [UBO_WINDOW uh:kScrollViewMaxHeight];
                }
                
                
                
                wself.scrollView.contentSize = [UBO_WINDOW fw:UB_WIDTH oh:wself.model.specificationsViewHeight+wself.model.promotionModel.topHeight+wself.model.promotionModel.middleHeight+wself.model.promotionModel.bottomHeight];
                wself.model.promotionViewHeight = wself.model.promotionModel.topHeight+wself.model.promotionModel.middleHeight+wself.model.promotionModel.bottomHeight;
                
                //重新布局视图
                wself.contentView.frame = CGRectOf([wself.ubo fx:UB_LEFT fy:UB_BOTTOM uy:kSizeMallViewMargin],
                                                  [wself.ubo fw:UB_WIDTH uh:kMainViewBaseHeight oh:wself.scrollViewHeight]);
                
                wself.confirmBtn.frame = CGRectOf([wself.contentView.ubo fx:UB_LEFT fy:UB_BOTTOM uy:-kConfirmButtonHeight],
                                                 [wself.contentView.ubo fw:UB_WIDTH uh:kConfirmButtonHeight]);
                
                wself.contentView.frame = CGRectOf([wself.ubo fx:UB_LEFT fy:UB_BOTTOM uy:-kMainViewBaseHeight oy:-wself.scrollViewHeight],
                                                  [wself.ubo fw:UB_WIDTH uh:kMainViewBaseHeight oh:wself.scrollViewHeight]);
            }];
        }
    }
}


@end

